package com.duoduo.common.fliter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Root角色过滤器</br>
 * 不具有Root角色的请求将被过滤
 */
@Component
public class RootRoleFilter implements Filter {

    /**
     * 核心鉴权操作执行域
     */
    @Autowired
    private StatelessRealm statelessRealm;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(isAccessAllowed(servletRequest,servletResponse)){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            throw new RuntimeException("没有权限！");
           // onAuthorizationFail(servletResponse,"没有权限！");
        }
    }

    @Override
    public void destroy() {

    }

//    private void onAuthorizationFail(ServletResponse servletResponse, String errorMsg) throws IOException {
//        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
//        // httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//        BaseResult result = BaseResult.failWithCodeAndMsg(401,errorMsg);
//        httpResponse.setCharacterEncoding("utf-8");
//        httpResponse.setContentType("application/json");
//        httpResponse.getWriter().write(JSONObject.toJSONString(result));
//    }

    // 判断是否有该角色的权限
    private boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String tokenStr = request.getHeader("token");
        if(tokenStr == null){// 请求头中没有Token
            return false;
        }
        /*try{
            return statelessRealm.hasRole(tokenStr, Role.ROOT.name());
        }catch (Exception e){
            return false;
        }*/
        return true;
    }
}
